package com.aliyun.heiyu.powermaster.server.rotary.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.heiyu.common.util.HttpUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.powermaster.proto.*;
import com.aliyun.heiyu.powermaster.server.rotary.contants.ModbusOrderContant;
import com.aliyun.heiyu.powermaster.server.rotary.contants.ProtocolContant;
import com.aliyun.heiyu.powermaster.server.rotary.dao.AirDAO;
import com.aliyun.heiyu.powermaster.server.rotary.dao.impl.AirDAOImpl;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.AirInformationDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.CloseConnectRes;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.ConnectReq;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.ConnectRes;
import com.aliyun.heiyu.powermaster.server.rotary.object.transit.ResTem;
import com.aliyun.heiyu.powermaster.server.rotary.service.ConnectManager;
import com.aliyun.heiyu.powermaster.server.rotary.service.IpcService;
import com.aliyun.heiyu.powermaster.server.rotary.utils.IpcDataUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 连接管理实现
 * @Author shun.zhang
 * @Date 2020/9/10 15:54
 **/
public class ConnectManagerImpl implements ConnectManager {
    private static Logger logger = LoggerFactory.getLogger(ConnectManagerImpl.class);

    private IpcService ipcService;
    private AirDAO airDAO;

    public ConnectManagerImpl() {
        this.airDAO = new AirDAOImpl();
        this.ipcService = new IpcServiceImpl();
    }

    /**
     * 设置空调的值
     *
     * @param request
     * @return
     */
    @Override
    public ControllReply setAirValue(ControllRequest request) {
        ControllReply.Builder builder = ControllReply.newBuilder();
        //1.判断格式值格式是否正确
        int value = 0;
        //判断guid是否为空
        if (StringUtil.isEmpty(request.getGuid())) {
            builder.setValue("guid不能为空");
            builder.setTime(request.getTime());
            return builder.build();
        }
        //判断guid是否存在
        AirInformationDTO air = airDAO.getAirBySn(request.getGuid());
        if (null == air) {
            builder.setGuid(request.getGuid());
            builder.setValue("设备不存在");
            builder.setTime(request.getTime());
            return builder.build();
        }
        try {
            value = Integer.valueOf(request.getValue());
        } catch (Exception e) {
            builder.setGuid(request.getGuid());
            builder.setValue("设置值格式有问题，请下去好好思考一下");
            builder.setTime(request.getTime());
            return builder.build();
        }
        if(17>value || value > 25){
            builder.setGuid(request.getGuid());
            builder.setValue("设置值范围为（17-25）请勿做危险动作");
            builder.setTime(request.getTime());
            return builder.build();
        }
        //2.判断值的范围
        String url = PropertiesUtil.getValue("serverIp.properties", "setAirUrl");
        String requestModbus = IpcDataUtil.potData(ProtocolContant.MODBUS, 1, ModbusOrderContant.OPERATION, 26, value);

        ResTem resTem = ipcService.sendOrderToIpc(url, requestModbus);
        if (null == resTem){
            logger.info("空调设置失败！！！");
        }else {
            logger.info("空调设置成功！！！");
        }
        builder.setGuid(request.getGuid());
        builder.setValue(request.getValue());
        builder.setTime(request.getTime());
        return builder.build();
    }

    /**
     * 设置空调的值
     *
     * @param request
     * @return
     */
    @Override
    public ControllReply setAirAlgoValue(ControllRequest request) {
        ControllReply.Builder builder = ControllReply.newBuilder();
        //1.判断格式值格式是否正确
        double value = 0;
        try {
            value = Double.valueOf(request.getValue());
        } catch (Exception e) {
            builder.setGuid(request.getGuid());
            builder.setValue("设置值格式有问题，请下去好好思考一下");
            builder.setTime(request.getTime());
            return builder.build();
        }
        if(17>value || value > 25){
            builder.setGuid(request.getGuid());
            builder.setValue("设置值范围为（17-25）请勿做危险动作");
            builder.setTime(request.getTime());
            return builder.build();
        }
        //2.判断值的范围
        String url = PropertiesUtil.getValue("serverIp.properties", "setAirUrl");
        String requestModbus = IpcDataUtil.potData(ProtocolContant.MODBUS, 1, ModbusOrderContant.OPERATION, 26, value);

        ResTem resTem = ipcService.sendOrderToIpc(url, requestModbus);
        if (null == resTem){
            logger.info("空调设置失败！！！");
        }else {
            logger.info("空调设置成功！！！");
        }
        builder.setGuid(request.getGuid());
        builder.setValue(request.getValue());
        builder.setTime(request.getTime());
        return builder.build();
    }

    /**
     * 添加设备空调
     *
     * @param request
     * @return
     */
    @Override
    public ControllReply addControllAir(ControllRequest request) {
        ControllReply.Builder builder = ControllReply.newBuilder();

        //判断guid是否为空
        if (StringUtil.isEmpty(request.getGuid())) {
            builder.setValue("guid不能为空");
            builder.setTime(request.getTime());
            return builder.build();
        }
        //判断guid是否存在
        AirInformationDTO air = airDAO.getAirBySn(request.getGuid());
        if(null == air){
            builder.setGuid(request.getGuid());
            builder.setValue("设备不存在");
            builder.setTime(request.getTime());
            return builder.build();
        }

        String url = PropertiesUtil.getValue("serverIp.properties", "addAirUrl");
        String requestModbus = IpcDataUtil.potData(ProtocolContant.MODBUS, 1, 11, 1, 1);

        ResTem resTem = ipcService.sendOrderToIpc(url, requestModbus);
        if (null == resTem) {
            logger.info("添加空调失败！！！");
        } else {
            logger.info("添加空调成功！！！");
        }
        builder.setGuid(request.getGuid());
        builder.setValue(request.getValue());
        builder.setTime(request.getTime());
        return builder.build();
    }

    /**
     * 建立连接
     *
     * @param request
     * @return
     */
    @Override
    public ConnectReply connect(ConnectRequest request) {
        ConnectReply.Builder builder = ConnectReply.newBuilder();
        //1.将request转化为ConnectReq
        ConnectReq req = new ConnectReq();
        req.setIp(request.getIp());
        req.setUsername(request.getUsername());
        req.setPa(request.getPassword());
        req.setLogin_time(request.getLoginTime());
        //2.调用动环接口
        ConnectRes connectRes = connectRatory(req);
        if (null == connectRes) {
            return null;
        }
        //3.将返回值进行转化
        return builder.setLoginTime(connectRes.getLogin_time())
            .setTimeout(connectRes.getTimeout())
            .setToken(connectRes.getToken())
            .build();
    }

    /**
     * 释放连接
     *
     * @param request
     * @return
     */
    @Override
    public CloseConnectReply closeConnect(ConnectRequest request) {
        CloseConnectReply.Builder builder = CloseConnectReply.newBuilder();
        //1.将request转化为CloseConnectReq
        ConnectReq req = new ConnectReq();
        req.setIp(request.getIp());
        req.setUsername(request.getUsername());
        req.setPa(request.getPassword());
        req.setLogin_time(request.getLoginTime());
        //2.调用动环接口
        CloseConnectRes close = closeConnectRatory(req);
        if (null == close) {
            return null;
        }
        //3.将返回值进行转化
        return builder.setIp(close.getIp())
            .setUsername(close.getUsername())
            .setPassword(close.getPa())
            .setLoginTime(close.getLogin_time())
            .build();
    }

    /**
     * 连接动环
     *
     * @param req
     * @return
     */
    private ConnectRes connectRatory(ConnectReq req) {
        String url = ":36800/v2/north/login";
        StringBuffer u = new StringBuffer();
        u.append("http://")
            .append(req.getIp())
            .append(url);
        String param = JSON.toJSONString(req);
        JSONObject object = HttpUtil.postRequest(param, u.toString());
        if (null == object) {
            return null;
        }
        return JSON.parseObject(object.toString(), ConnectRes.class);
    }

    /**
     * 释放动环连接
     *
     * @param req
     * @return
     */
    private CloseConnectRes closeConnectRatory(ConnectReq req) {
        String url = ":36800/v2/north/close";
        StringBuffer u = new StringBuffer();
        u.append("http://")
            .append(req.getIp())
            .append(url);
        String param = JSON.toJSONString(req);
        JSONObject object = HttpUtil.postRequest(param, u.toString());
        if (null == object) {
            return null;
        }
        return JSON.parseObject(object.toString(), CloseConnectRes.class);
    }

}
